#include <mod/include/ADC.h>
#include <mod/include/TWI.h>

/*    ADC values are read through a Two-Wire Interface to which
      AD converter 
      */

/**   @fn	ADC_Init()
      @brief	initializes the external ADC module
      @return	void
      */
void ADC_Init(void){
  unsigned char adresses[3]={0x02,0x00,0x00};
  TWI_Start(0x21,0);
  TWI_Write(0x02);
  TWI_Write(0x00);
  TWI_Write(0x00);
  TWI_Stop();
}

/**   @fn	int ADC_Read(channel)
      @brief	reads a value from a given channel of the external ADC
      @param	channel	
      @return	long integer w/ ADC value
      */
long int ADC_Read(unsigned short int channel){
  long int data,temp,adress;
  adress=((channel&0x07)|0x08)<<4;
  TWI_Start1(0x21,1,&adress,1);
  TWI_Repeated_Start();
  data=TWI_Read();
  while(data==-1){
    data=TWI_Read();
  }
  temp=data<<8;
  data=TWI_Read();
  while(data==-1){
    data=TWI_Read();
  }
  temp|=data;
  TWI_Stop();
  return temp;
}

/**   @fn ADC_Read_Multiple(channel_select, total_number_used_ADCS, *result)
      @brief  reads a values from multiple channels of the external ADC
      @param  channel_select
      @param  total_number_used_ADCS
      @param  *result
      @return void
      */
void ADC_Read_Multiple(unsigned char channel_select, unsigned char total_number_used_ADCS, unsigned int *result){
  long int data,temp,adress,loop;
  adress=0x70;
  TWI_Start(0x21,0);
  TWI_Write(0x02);
  TWI_Write(channel_select<<4);
  TWI_Write((channel_select>>4)&0x0F);
  TWI_Stop();
  loop=100;
  while(loop--);
  TWI_Start1(0x21,1,&adress,1);
  TWI_Repeated_Start();
  for(loop=0;loop<total_number_used_ADCS;loop++){
    data=TWI_Read();
    while(data==-1){
      data=TWI_Read();
    }
    *(result+loop)=0;
    *(result+loop)=data<<8;
    data=TWI_Read();
    while(data==-1){
      data=TWI_Read();
    }
    (*(result+loop))|=data;
  }
  TWI_Stop();
}

/*   long int data,loop;   
   TWI_Start(0x21,0);
   TWI_Write(0x02);
   TWI_Write(channel_select<<4);
   TWI_Write((channel_select>>4)&0x0F);
   TWI_Start(0x21,0);
   TWI_Write(0x70);
   TWI_Start(0x21,1);
*/
